package com.csdj.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.csdj.reggie.commcn.CustomException;
import com.csdj.reggie.dto.SetmealDto;
import com.csdj.reggie.entity.Setmeal;
import com.csdj.reggie.entity.SetmealDish;
import com.csdj.reggie.mapper.SetmealMapper;
import com.csdj.reggie.service.SetmealDishService;
import com.csdj.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper,Setmeal> implements SetmealService {
    @Autowired
    private SetmealDishService setmealDishService;

    /**
     * 添加套餐,保存菜品和套餐的关联关系
     * @param setmealDto
     */
    @Override
    @Transactional
    public void savaWithDish(SetmealDto setmealDto) {
        // 保存套餐的基本信息，操作setmeal，执行insert操作
        this.save(setmealDto);

        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes.stream().map((item)->{
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());


        // 保存套餐和菜品的关联信息，操作setmeal_dish，执行insert操作
        setmealDishService.saveBatch(setmealDishes);
    }

    /**
     * 删除套餐的同时清除菜品关联的数据
     * @param ids
     */
    @Override
    @Transactional
    public void removeWithDish(List<Long> ids) {
        // 查询套餐状态是否可用删除
        LambdaQueryWrapper<Setmeal> queryWrapper=new LambdaQueryWrapper<>();
        // 选择被选择的id
        queryWrapper.in(Setmeal::getId,ids);
        // 选择停售的套餐
        queryWrapper.eq(Setmeal::getStatus,1);

        // 查询是否有在售套餐
        if (this.count(queryWrapper)>0){
            throw new CustomException("套餐正在售卖中，不能删除");
        }
        // 删除套餐
        this.removeByIds(ids);

        // 创建条件构造器
        LambdaQueryWrapper<SetmealDish> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(SetmealDish::getSetmealId,ids);
        // 删除套餐关联商品的数据
        setmealDishService.remove(lambdaQueryWrapper);

    }
}
